<template>
  <a-flex align="start" :gap="16" :style="{ overflow: 'auto' }">
    <div>
      <a-button type="primary" :disabled="status === 'pending'" @click="request">
        Agent Request
      </a-button>
    </div>
    <div>
      <ThoughtChain
        :style="{ marginLeft: '16px' }"
        :items="[
          {
            title: 'Agent Request Log',
            status: status,
            icon: status === 'pending' ? h(LoadingOutlined) : h(TagsOutlined),
            description:
              status === 'error' &&
              agent.config.baseURL === BASE_URL + PATH &&
              'Please replace the BASE_URL, PATH, MODEL, API_KEY with your own values.',
            content: h(Descriptions, { column: 1 }, {
              default: () => [
                h(Descriptions.Item, { label: 'Status' }, () => status || '-'),
                h(Descriptions.Item, { label: 'Update Times' }, () => lines.length)
              ]
            })
          }
        ]"
      />
    </div>
  </a-flex>
</template>

<script setup lang="ts">
import { ref, h } from 'vue'
import { LoadingOutlined, TagsOutlined } from '@ant-design/icons-vue'
import { Button, Descriptions } from 'ant-design-vue'
import {ThoughtChain, useXAgent, XRequest} from 'ant-design-x-vue'
import type { ThoughtChainItem } from 'ant-design-x-vue'
import sysConfig from "@/config";
import tool from "@/utils/tool";

defineOptions({ name: 'AgentPreset' })

/**
 * 🔔 Please replace the BASE_URL, PATH, MODEL, API_KEY with your own values.
 */
const BASE_URL = 'http://127.0.0.1:82'
const PATH = '/chat/completions'
const MODEL = 'xdeepseekv3'
/** 🔥🔥 Its dangerously! */
const API_KEY = 'your-key'

interface YourMessageType {
  role: string
  content: string
}

const status = ref<ThoughtChainItem['status']>()
const lines = ref<Record<string, string>[]>([])

const [ agent ] = useXAgent<YourMessageType>({
  baseURL: BASE_URL + PATH,
  model: MODEL,
	token: 'aaaa'
  // dangerouslyApiKey: API_KEY
})
const exampleRequest = XRequest({
	baseURL: BASE_URL + PATH,
	model: MODEL,
	fetch: doFetch,
});

async function doFetch() {
	const token = tool.data.get('TOKEN')

	// 创建SSE连接
	const response = await fetch(`http://127.0.0.1:82/chat/completions`, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			'Accept': 'text/event-stream',
			'token': sysConfig.TOKEN_PREFIX + token
		},
		body: JSON.stringify({
			messages: [{ role: 'user', content: '你好' }],
			model: MODEL,
			stream: true
		}),
	})
	return 	response;
}

async function request() {
  status.value = 'pending'

  // agent.value.request(
	await exampleRequest.create(
    {
      messages: [{ role: 'user', content: 'hello, who are u?' }],
      stream: true,
    },
    {
      onSuccess: (messages) => {
        status.value = 'success'
        console.log('onSuccess', messages)
      },
      onError: (error) => {
        status.value = 'error'
        console.error('onError', error)
      },
      onUpdate: (msg) => {
        // @ts-expect-error
        lines.value = [...lines.value, msg]
        console.log('onUpdate', msg)
      },
    },
  )
}
</script>
